<?php

declare(strict_types=1);

namespace App\Middleware;

use App\Constants\ReturnCode;
use Hyperf\Di\Annotation\Inject;
use Hyperf\HttpServer\Contract\RequestInterface;
use Hyperf\HttpServer\Contract\ResponseInterface as HttpResponse;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\MiddlewareInterface;
use Psr\Http\Server\RequestHandlerInterface;
use Psr\SimpleCache\CacheInterface;

class AuthMiddleware implements MiddlewareInterface
{
    #[Inject]
    protected RequestInterface $request;

    #[Inject]
    protected HttpResponse $response;

    #[Inject]
    protected CacheInterface $cache;

    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
    {
        // 根据具体业务判断逻辑走向，这里假设用户携带的token有效
        $token = $this->request->header('Authorization', '');

        if (!$token) {
            $data = [
                'code' => ReturnCode::NOT_AUTH->value,
                'msg'  => '缺少认证信息 : Authorization',
                'data' => []
            ];

            return $this->response->json($data);
        }

        // 获取用户信息
        $user_info = $this->cache->get('Authorization:' . $token);

        if (empty($user_info)) {
            $data = [
                'code' => ReturnCode::NOT_AUTH,
                'msg'  => 'token已过期',
                'data' => []
            ];

            return $this->response->json($data);
        }

        return $handler->handle($request);
    }
}
